<template>
  <view class="license-container">
    <!-- 车辆信息头部 -->
    <view class="vehicle-header">
      <view class="vehicle-info">
        <uni-icons type="shop" size="24" color="#1890ff"></uni-icons>
        <text class="vehicle-plate">{{ vehicleInfo.vehiclePlate }}</text>
      </view>
      <text class="vehicle-type">{{ getVehicleTypeName(vehicleInfo.vehicleType) }}</text>
    </view>
    
    <!-- 证件分类展示 -->
    <view class="license-sections">
      <!-- 行驶证 -->
      <view class="license-section">
        <view class="section-header">
          <view class="section-title">
            <view class="title-icon driving"></view>
            <text>行驶证</text>
          </view>
          <button class="upload-btn" @click="chooseImage('driving')">
            <uni-icons type="camera" size="18" color="#1890ff"></uni-icons>
            上传
          </button>
        </view>
        
        <view v-if="drivingLicenseImages.length > 0" class="license-grid">
          <view 
            v-for="(image, index) in drivingLicenseImages" 
            :key="index"
            class="license-item"
          >
            <image 
              :src="image" 
              class="license-image" 
              mode="aspectFill"
              @click="previewImage(drivingLicenseImages, index)"
            ></image>
            <view class="image-actions">
              <view class="action-btn" @click="previewImage(drivingLicenseImages, index)">
                <uni-icons type="eye" size="20" color="#fff"></uni-icons>
              </view>
              <view class="action-btn delete" @click="deleteImage('driving', index)">
                <uni-icons type="trash" size="20" color="#fff"></uni-icons>
              </view>
            </view>
            <text class="image-label">{{ index === 0 ? '正页' : '副页' }}</text>
          </view>
        </view>
        
        <view v-else class="empty-state">
          <uni-icons type="image" size="48" color="#d9d9d9"></uni-icons>
          <text class="empty-text">暂无行驶证照片</text>
          <button class="empty-upload-btn" @click="chooseImage('driving')">
            立即上传
          </button>
        </view>
      </view>
      
      <!-- 营运证 -->
      <view class="license-section">
        <view class="section-header">
          <view class="section-title">
            <view class="title-icon operating"></view>
            <text>道路运输证</text>
          </view>
          <button class="upload-btn" @click="chooseImage('operating')">
            <uni-icons type="camera" size="18" color="#1890ff"></uni-icons>
            上传
          </button>
        </view>
        
        <view v-if="operatingLicenseImages.length > 0" class="license-grid">
          <view 
            v-for="(image, index) in operatingLicenseImages" 
            :key="index"
            class="license-item"
          >
            <image 
              :src="image" 
              class="license-image" 
              mode="aspectFill"
              @click="previewImage(operatingLicenseImages, index)"
            ></image>
            <view class="image-actions">
              <view class="action-btn" @click="previewImage(operatingLicenseImages, index)">
                <uni-icons type="eye" size="20" color="#fff"></uni-icons>
              </view>
              <view class="action-btn delete" @click="deleteImage('operating', index)">
                <uni-icons type="trash" size="20" color="#fff"></uni-icons>
              </view>
            </view>
            <text class="image-label">{{ index === 0 ? '正页' : '副页' }}</text>
          </view>
        </view>
        
        <view v-else class="empty-state">
          <uni-icons type="image" size="48" color="#d9d9d9"></uni-icons>
          <text class="empty-text">暂无营运证照片</text>
          <button class="empty-upload-btn" @click="chooseImage('operating')">
            立即上传
          </button>
        </view>
      </view>
      
      <!-- 其他证件（预留扩展） -->
      <view class="license-section">
        <view class="section-header">
          <view class="section-title">
            <view class="title-icon other"></view>
            <text>其他证件</text>
          </view>
          <button class="upload-btn" @click="chooseImage('other')">
            <uni-icons type="camera" size="18" color="#1890ff"></uni-icons>
            上传
          </button>
        </view>
        
        <view v-if="otherLicenseImages.length > 0" class="license-grid">
          <view 
            v-for="(image, index) in otherLicenseImages" 
            :key="index"
            class="license-item"
          >
            <image 
              :src="image" 
              class="license-image" 
              mode="aspectFill"
              @click="previewImage(otherLicenseImages, index)"
            ></image>
            <view class="image-actions">
              <view class="action-btn" @click="previewImage(otherLicenseImages, index)">
                <uni-icons type="eye" size="20" color="#fff"></uni-icons>
              </view>
              <view class="action-btn delete" @click="deleteImage('other', index)">
                <uni-icons type="trash" size="20" color="#fff"></uni-icons>
              </view>
            </view>
          </view>
        </view>
        
        <view v-else class="empty-state">
          <uni-icons type="image" size="48" color="#d9d9d9"></uni-icons>
          <text class="empty-text">暂无其他证件</text>
          <button class="empty-upload-btn" @click="chooseImage('other')">
            立即上传
          </button>
        </view>
      </view>
    </view>
    
    <!-- 保存按钮 -->
    <view class="bottom-actions" v-if="hasChanges">
      <button class="save-btn" @click="saveChanges">保存更改</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      vehicleId: null,
      vehicleInfo: {},
      drivingLicenseImages: [],
      operatingLicenseImages: [],
      otherLicenseImages: [],
      originalImages: {
        driving: [],
        operating: [],
        other: []
      },
      vehicleTypes: {
        '0': '货车',
        '1': '面包车',
        '2': '小型车',
        '3': '其他'
      },
      hasChanges: false
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.vehicleId = options.id
      this.loadVehicleInfo()
    }
  },
  
  methods: {
    // 加载车辆信息
    async loadVehicleInfo() {
      try {
        uni.showLoading({ title: '加载中...' })
        const res = await this.$http.get(`/system/vehicle/${this.vehicleId}`)
        
        if (res.code === 200 && res.data) {
          this.vehicleInfo = res.data
          
          // 处理证件图片
          if (res.data.drivingLicensePhoto) {
            this.drivingLicenseImages = res.data.drivingLicensePhoto.split(',').filter(img => img)
            this.originalImages.driving = [...this.drivingLicenseImages]
          }
          if (res.data.operatingLicensePhoto) {
            this.operatingLicenseImages = res.data.operatingLicensePhoto.split(',').filter(img => img)
            this.originalImages.operating = [...this.operatingLicenseImages]
          }
          // 其他证件预留
          this.originalImages.other = []
        }
      } catch (error) {
        console.error('加载车辆信息失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 获取车辆类型名称
    getVehicleTypeName(type) {
      return this.vehicleTypes[type] || '未知'
    },
    
    // 选择图片
    chooseImage(type) {
      let maxCount = 2
      let currentImages = []
      
      if (type === 'driving') {
        currentImages = this.drivingLicenseImages
      } else if (type === 'operating') {
        currentImages = this.operatingLicenseImages
      } else {
        currentImages = this.otherLicenseImages
        maxCount = 9 // 其他证件最多9张
      }
      
      const remainingCount = maxCount - currentImages.length
      if (remainingCount <= 0) {
        uni.showToast({
          title: `最多上传${maxCount}张图片`,
          icon: 'none'
        })
        return
      }
      
      uni.chooseImage({
        count: remainingCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 直接使用临时文件路径，不再转换为base64
          res.tempFilePaths.forEach(path => {
            if (type === 'driving') {
              this.drivingLicenseImages.push(path)
            } else if (type === 'operating') {
              this.operatingLicenseImages.push(path)
            } else {
              this.otherLicenseImages.push(path)
            }
            this.checkChanges()
          })
        }
      })
    },
    
    // 删除图片
    deleteImage(type, index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张证件照片吗？',
        success: (res) => {
          if (res.confirm) {
            if (type === 'driving') {
              this.drivingLicenseImages.splice(index, 1)
            } else if (type === 'operating') {
              this.operatingLicenseImages.splice(index, 1)
            } else {
              this.otherLicenseImages.splice(index, 1)
            }
            this.checkChanges()
          }
        }
      })
    },
    
    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: current
      })
    },
    
    // 检查是否有更改
    checkChanges() {
      const drivingChanged = JSON.stringify(this.drivingLicenseImages) !== JSON.stringify(this.originalImages.driving)
      const operatingChanged = JSON.stringify(this.operatingLicenseImages) !== JSON.stringify(this.originalImages.operating)
      const otherChanged = JSON.stringify(this.otherLicenseImages) !== JSON.stringify(this.originalImages.other)
      
      this.hasChanges = drivingChanged || operatingChanged || otherChanged
    },
    
    // 保存更改
    async saveChanges() {
      try {
        uni.showLoading({ title: '保存中...' })
        
        const updateData = {
          vehicleId: this.vehicleId,
          drivingLicensePhoto: this.drivingLicenseImages.join(','),
          operatingLicensePhoto: this.operatingLicenseImages.join(',')
          // 其他证件字段预留
        }
        
        const res = await this.$http.put('/system/vehicle', updateData)
        
        if (res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 更新原始数据
          this.originalImages.driving = [...this.drivingLicenseImages]
          this.originalImages.operating = [...this.operatingLicenseImages]
          this.originalImages.other = [...this.otherLicenseImages]
          this.hasChanges = false
        } else {
          uni.showToast({
            title: res.msg || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('保存证件失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style scoped>
.license-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

/* 车辆头部信息 */
.vehicle-header {
  background: #fff;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.vehicle-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.vehicle-plate {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.vehicle-type {
  font-size: 26rpx;
  color: #666;
  padding: 8rpx 16rpx;
  background: #f0f0f0;
  border-radius: 20rpx;
}

/* 证件区块 */
.license-sections {
  padding: 20rpx;
}

.license-section {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 16rpx;
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.title-icon {
  width: 8rpx;
  height: 32rpx;
  border-radius: 4rpx;
}

.title-icon.driving {
  background: #1890ff;
}

.title-icon.operating {
  background: #52c41a;
}

.title-icon.other {
  background: #fa8c16;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 24rpx;
  background: #e6f7ff;
  color: #1890ff;
  border: 1rpx solid #91d5ff;
  border-radius: 20rpx;
  font-size: 26rpx;
}

/* 证件网格 */
.license-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  padding: 30rpx;
}

.license-item {
  position: relative;
  width: calc(50% - 10rpx);
}

.license-image {
  width: 100%;
  height: 240rpx;
  border-radius: 8rpx;
  background: #f5f5f5;
}

.image-actions {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 8rpx;
}

.license-item:active .image-actions {
  opacity: 1;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.delete {
  background: #ff4d4f;
}

.image-label {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 24rpx;
  text-align: center;
  padding: 8rpx;
  border-radius: 0 0 8rpx 8rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin: 20rpx 0;
}

.empty-upload-btn {
  padding: 16rpx 32rpx;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: #fff;
  border: none;
  border-radius: 30rpx;
  font-size: 28rpx;
}

/* 底部操作 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: #fff;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
}
</style>